<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>
  <ul>
    <li><a href="/home">首页</a></li>
    <li><a href="/about">关于</a></li>
  </ul>

  <!-- 当 url 变更后，展示对应的代码片段 -->
  <div id="root"></div>

  <script>
    const routes = [
      {
        path: '/home',
        component: (val) => {
          return `<h1>首页页面${val}</h1>`
        }
      },
      {
        path: '/about',
        component: () => {
          return '<h1>关于页面</h1>'
        }
      }
    ]

    let routerView = document.getElementById('root')


    window.addEventListener('DOMContentLoaded', () => {
      onLoad()
    })

    window.addEventListener('popstate', () => {  // 监听浏览器的前进后退事件
      renderView(location.pathname)
    })


    function onLoad() {  // 渲染对应的组件
      let linkList = document.querySelectorAll('a[href]')
      linkList.forEach(el => {
        el.addEventListener('click', function(e) {
          e.preventDefault()  // 阻止默认行为
          history.pushState(null, '', el.getAttribute('href'))  // 进入浏览器的缓存栈，但是不受前进后退事件的影响

          // console.log(location);
          
          renderView(location.pathname)
        })
      })
      
    }


    function renderView(url) {
      const index = routes.findIndex(item => {
        return item.path === url
      })
      routerView.innerHTML = routes[index].component()
    }
  </script>
</body>
</html>